package wxapp

import (
	"encoding/json"
	"fmt"
	"huling/utils/results"
	utils "huling/utils/tool"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

// 获取账号和产品
func GetUserProduct(context *gin.Context) {
	//当前用户
	wxuid := context.DefaultQuery("wxuid", "0")
	//获取产品
	product_id, _ := DB().Table("wxapp_product_select").Where("wxuid", wxuid).Pluck("product_id")
	my_product_id, _ := DB().Table("wxapp_product").Where("uid", wxuid).Pluck("id")
	product_ids := mergeArr(product_id.([]interface{}), my_product_id.([]interface{}))
	productList, _ := DB().Table("wxapp_product").WhereIn("id", product_ids).Fields("id,image,name,des,price,link_type,link,appid,path,extraData,createtime").Order("id desc").Get()
	//获取用户
	data, err := DB().Table("wxapp_user").Where("id", wxuid).Fields("id,avatar,name,nickname,province,city,mobile,email,company,personal_content,company_content,weixin,wx_qrcode,address,tplid,position,personal_content_show,company_content_show,wxacode,wxacodedf").First()
	if err == nil {
		if data["address"] == "" && data["province"] != "" {
			data["address"] = data["province"].(string) + " " + data["city"].(string)
		}
		if data["name"] == "" {
			data["name"] = data["nickname"]
		}
		s_plist := make([]interface{}, 0)
		if productList != nil {
			for _, val := range productList {
				if val["link_type"] == "wxapp" {
					if strings.Contains(val["path"].(string), "?") {
						val["path"] = fmt.Sprintf("%s&mobile=%s", val["path"], data["mobile"])
					} else {
						val["path"] = fmt.Sprintf("%s?mobile=%s", val["path"], data["mobile"])
					}
				}
				s_plist = append(s_plist, val)
			}
		}

		//1.2获取猫车服产品
		var access_parameter map[string]interface{}
		var mm_product []interface{}
		mmcf_data, err := Get_x("http://114.117.246.205:7001/publicapi/sitegoods/sitegoodslist2?token=pxd119")
		if err != nil {
			mm_product = make([]interface{}, 0)
		} else {
			if err := json.Unmarshal([]byte(mmcf_data), &access_parameter); err == nil {
				if access_parameter["data"] != nil {
					var item map[string]interface{}
					product_ids_mm, _ := DB().Table("wxapp_product_select").Where("wxuid", wxuid).Pluck("product_id")
					for _, val := range access_parameter["data"].([]interface{}) {
						b_val, _ := json.Marshal(val)
						json.Unmarshal([]byte(b_val), &item)
						if resd := IsContain_str(product_ids_mm.([]interface{}), fmt.Sprintf("%s%v", "mm_", item["id"])); resd == true {
							tim, _ := time.Parse("2006-01-02 15:04:05", fmt.Sprintf("%s%s", "", item["createTime"]))
							mm_product = append(mm_product, map[string]interface{}{
								"id":        fmt.Sprintf("%s%v", "mm_", item["id"]),
								"image":     item["cover"],
								"name":      item["title"],
								"price":     item["price"],
								"des":       "",
								"link_type": "wxapp",
								"appid":     "wx31d612c4b628d5cb",
								"path":      fmt.Sprintf("pages/product/detail/detail?goodId=%v&mobile=%s", item["id"], data["mobile"]),
								// "path":       fmt.Sprintf("%s%v", "pages/product/detail/detail?goodId=", item["id"]),
								"extraData":  "",
								"createtime": tim.Unix(),
							})
						}
					}
				}
			} else {
				mm_product = make([]interface{}, 0)
			}
		}

		//2获取卡片样式
		style, _ := DB().Table("wxapp_tpl").Where("id", data["tplid"]).Fields("type,bgtype,image,bg_color,color,icon_bg_color,icon_color,NavigationBar_frontColor,NavigationBar_backgroundColor,topbgcolor,topbgcolorbottom,btn_border_color,btn_font_color,btn_linear_left,btn_linear_right").First()
		if style != nil && style["image"] != "" {
			rooturl, _ := DB().Table("common_config").Where("keyname", "rooturl").Value("keyvalue")
			style["image"] = rooturl.(string) + style["image"].(string)
		}
		//获取自定义背景
		user_tpl_image, _ := DB().Table("wxapp_user_tpl").Where("uid", wxuid).Where("tplid", data["tplid"]).Value("image")
		if user_tpl_image != nil && user_tpl_image != "" {
			rooturl, _ := DB().Table("common_config").Where("keyname", "rooturl").Value("keyvalue")
			style["image"] = rooturl.(string) + user_tpl_image.(string)
			style["bgtype"] = 1
		}
		//刷新用户token
		token := context.Request.Header.Get("Authorization")
		var newtoken interface{}
		if token != "0" {
			newtoken = utils.Refresh(token)
		}
		results.Success(context, "获取账号和产品列表", map[string]interface{}{"data": data, "plist": mergeArr(s_plist, mm_product), "style": style}, newtoken)
	} else {
		results.Failed(context, "获取账号和产品失败", err)
	}
}
